﻿using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System;

namespace QFramework
{
    public class MyItemKitSaveHandler : IItemKitSaveHandler
    {
        [Serializable]
        public class SaveData
        {
            public List<GroupData> Groups;
        }
        [Serializable]
        public class GroupData
        {
            public string Key;
            public List<SlotData> Slots;
        }
        [Serializable]
        public class SlotData
        {
            public string ItemKey;
            public int Count;
        }

        public void Save(Dictionary<string, SlotGroup> dictSlotGroup)
        {
            var saveData = new SaveData()
            {
                Groups = dictSlotGroup.Values.Select(group => new GroupData()
                {
                    Key = group.Key,
                    Slots = group.Slots.Select(slot => new SlotData()
                    {
                        ItemKey = slot.Item?.GetKey,
                        Count = slot.Count,
                    }).ToList(),
                }).ToList(),
            };
            PlayerPrefs.SetString("my_item_kit", JsonUtility.ToJson(saveData));
        }

        public void Load(Dictionary<string, SlotGroup> dictSlotGroup)
        {
            var json = PlayerPrefs.GetString("my_item_kit", string.Empty);
            if (json.IsNotNullAndEmpty())
            {
                var saveData = JsonUtility.FromJson<SaveData>(json);
                foreach (var groupData in saveData.Groups)
                {
                    dictSlotGroup.TryGetValue(groupData.Key, out SlotGroup slotGroup);
                    slotGroup ??= ItemKit.CreateSlotGroup(groupData.Key);

                    for (int i = 0; i < groupData.Slots.Count; i++)
                    {
                        var slot = groupData.Slots[i];
                        var item = slot.ItemKey.IsNullOrEmpty() ? null : ItemKit.DictItem[slot.ItemKey];
                        if (i < slotGroup.Slots.Count)
                        {
                            slotGroup.Slots[i].Item = item;
                            slotGroup.Slots[i].Count = slot.Count;
                            slotGroup.Slots[i].OnChanged.Trigger();
                        }
                        else
                        {
                            slotGroup.CreateSlot(item, slot.Count);
                        }
                    }
                }
            }
        }

        public void Clear()
        {
            PlayerPrefs.DeleteKey("my_item_kit");
        }
    }
}
